import {
    ApiResponse,
    ComfyOneConfig,
    WorkflowsResponse,
    WorkflowResponse,
    CreateWorkflowRequest,
    UpdateWorkflowRequest,
    CreateTaskRequest,
    TaskHistoryParams,
    TaskHistoryResponse,
    InstancesResponse,
    CreateInstanceRequest,
    CreateTaskResponse,
    TaskData,
} from "~/models";

// ComfyOne API 配置
const BASE_URL = "https://pandora-server-cf.onethingai.com";

// const INSTANCE_ID = "ym12s4ghuiot810e-7350k8lg";

export const TOKEN = "04ff929b3bdbb44da653bbe2d5448aa6";

export const WORKFLOW_ID = "6778ce3d729479a363552760";

export const T2I_WORKFLOW_ID = "67793442729479a3635528d5";

export const I2I_WORKFLOW_ID = "6781e948729479a363553e35";

export const TRANSFER_WORKFLOW_ID = "67821283729479a363553f57";

// 创建请求头
const createHeaders = (token: string, contentType?: string) => {
    const headers = new Headers();
    headers.set("Authorization", `Bearer ${token}`);
    if (contentType !== "file") {
        headers.set("Content-Type", contentType || "application/json");
    }
    return headers;
};

// ComfyOne API 类
export class ComfyOneAPI {
    private token: string;

    constructor(config: ComfyOneConfig) {
        this.token = config.token;
    }

    // 通用请求方法
    private async request<T>(
        endpoint: string,
        method: string = "GET",
        body?: unknown,
        contentType?: string
    ): Promise<T> {
        const response = await fetch(`${BASE_URL}${endpoint}`, {
            method,
            headers: createHeaders(this.token, contentType),
            body:
                body instanceof FormData
                    ? body
                    : body
                    ? JSON.stringify(body)
                    : undefined,
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.statusText}`);
        }

        const data = await response.json();
        return data as T;
    }

    // 获取工作流列表
    async getWorkflows(): Promise<WorkflowsResponse> {
        return this.request<WorkflowsResponse>("/v1/workflows");
    }

    // 创建工作流
    async createWorkflow(
        workflowData: CreateWorkflowRequest
    ): Promise<WorkflowResponse> {
        return this.request<WorkflowResponse>(
            "/v1/workflows",
            "POST",
            workflowData
        );
    }

    // 获取特定工作流详情
    async getWorkflowById(workflowId: string): Promise<WorkflowResponse> {
        return this.request<WorkflowResponse>(`/v1/workflows/${workflowId}`);
    }

    // 更新工作流
    async updateWorkflow(
        workflowId: string,
        workflowData: UpdateWorkflowRequest
    ): Promise<WorkflowResponse> {
        return this.request<WorkflowResponse>(
            `/v1/workflows/${workflowId}`,
            "PUT",
            workflowData
        );
    }

    // 删除工作流
    async deleteWorkflow(workflowId: string): Promise<ApiResponse<void>> {
        return this.request<ApiResponse<void>>(
            `/v1/workflows/${workflowId}`,
            "DELETE"
        );
    }

    // 创建任务
    async createTask(
        taskData: CreateTaskRequest
    ): Promise<ApiResponse<CreateTaskResponse>> {
        return this.request<ApiResponse<CreateTaskResponse>>(
            "/v1/prompts",
            "POST",
            taskData
        );
    }

    // 获取任务状态
    async getTaskStatus(taskId: string): Promise<ApiResponse<TaskData>> {
        return this.request<ApiResponse<TaskData>>(
            `/v1/prompts/${taskId}/status`
        );
    }

    // 获取任务历史列表
    async getTaskHistory(
        params?: TaskHistoryParams
    ): Promise<TaskHistoryResponse> {
        const queryParams = new URLSearchParams();
        if (params?.page) queryParams.append("page", params.page.toString());
        if (params?.size) queryParams.append("size", params.size.toString());
        if (params?.status) queryParams.append("status", params.status);

        return this.request<TaskHistoryResponse>(`/v1/prompts`);
    }

    // 取消任务
    async cancelTask(taskId: string): Promise<ApiResponse<void>> {
        return this.request<ApiResponse<void>>(
            `/v1/prompts/${taskId}/cancel`,
            "POST"
        );
    }

    // 获取实例列表
    async getInstances(): Promise<InstancesResponse> {
        return this.request<InstancesResponse>("/v1/instances");
    }

    // 添加实例
    async addInstance(
        instanceData: CreateInstanceRequest
    ): Promise<ApiResponse<void>> {
        return this.request<ApiResponse<void>>(
            "/v1/instances",
            "POST",
            instanceData
        );
    }

    // 删除实例
    async deleteInstance(instanceId: string): Promise<ApiResponse<void>> {
        return this.request<ApiResponse<void>>(
            `/v1/instances/${instanceId}`,
            "DELETE"
        );
    }

    // 上传文件
    async uploadFile(file: File): Promise<ApiResponse<{ Path: string }>> {
        const formData = new FormData();
        formData.append("file", file);

        return this.request<ApiResponse<{ Path: string }>>(
            "/v1/files",
            "POST",
            formData,
            "file"
        );
    }
}

// 导出创建API实例的工厂函数
export const createComfyOneAPI = (
    config: ComfyOneConfig = { token: TOKEN }
) => {
    return new ComfyOneAPI(config);
};
